package apps.softtech.fastmarket;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import apps.softtech.Utility.ApplicationConstants;
import apps.softtech.Utility.FileUtility;
import apps.softtech.Utility.HttpRequest;

public class ActivityMain extends Activity {

	/**
	 * nguoi nao dung key nay de sua file activity
	 */
	final int CASE_MUI = 1;
	final int CASE_HOAI = 2;
	final int CASE_QUAN = 3;
	final int CASE_PHUOC = 4;
	
	Context mContext;
	public static final String PROPERTY_REG_ID = "registration_id";
	private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
	static String REG_ID = "";
	/**
		 * 
		 */
	GoogleCloudMessaging gcm;
	static final String TAG = "GCMDemo";
	/**
	 * Substitute you own sender ID here. This is the project number got
	 * 
	 */
	String SENDER_ID = "202517753016";
	
	String SAVE_FILE = "regid";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mContext = this;
		registerGCM();
		startCodeActvitity(CASE_PHUOC);
	}

	/**
	 * get gcm reg id restart this activity to register gcm
	 * 
	 * @param context
	 * @return
	 */
	public static String getRegId(Context context) {
		if (REG_ID.isEmpty()) {
			Intent intent = new Intent(context, ActivityMain.class);
			context.startActivity(intent);
			((Activity) context).finish();
		}
		return REG_ID;
	}

	/**
	 * register gcm
	 */
	public void registerGCM() {
		if (checkPlayServices()) {
			Log.v("", "This device is  supported.");
			FileUtility fu = new FileUtility();
			gcm = GoogleCloudMessaging.getInstance(mContext);
			REG_ID = fu.LoadContentFile(mContext, SAVE_FILE);
			if (REG_ID.isEmpty()) {
				registerInBackground();
			}
		}
	}

	/**
	 * register id
	 */
	private void registerInBackground() {
		new AsystaskGCM().execute();
	}

	/**
	 * check google play service
	 * 
	 * @return
	 */
	private boolean checkPlayServices() {
		int resultCode = GooglePlayServicesUtil
				.isGooglePlayServicesAvailable(ActivityMain.this);
		if (resultCode != ConnectionResult.SUCCESS) {
			if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
				GooglePlayServicesUtil.getErrorDialog(resultCode,
						ActivityMain.this, PLAY_SERVICES_RESOLUTION_REQUEST)
						.show();
			}
			return false;
		}
		return true;
	}

	class AsystaskGCM extends AsyncTask<String, String, String> {
		int success;

		@Override
		protected String doInBackground(String... params) {
			String msg = "";
			try {
				if (gcm == null) {
					gcm = GoogleCloudMessaging.getInstance(ActivityMain.this);
				}
				REG_ID = gcm.register(SENDER_ID);//
				msg = "Device registered, registration ID="
						+ ApplicationConstants.RED_ID;
				// request server
				if (REG_ID != null || REG_ID != "") {
					sendRegistrationIdToBackend();
				}
			} catch (Exception ex) {
				msg = "Error :" + ex.getMessage();
			}
			return msg;
		}

		// /**
		// * Stores the registration ID and app versionCode
		// */
		// private void storeRegistrationId(Context context, String regId) {
		// final SharedPreferences prefs = getGCMPreferences(context);
		// int appVersion = getAppVersion(context);
		// Log.i(TAG, "Saving regId on app version " + appVersion);
		// SharedPreferences.Editor editor = prefs.edit();
		// editor.putString(PROPERTY_REG_ID, regId);
		// editor.putInt(PROPERTY_APP_VERSION, appVersion);
		// editor.commit();
		// }
		/**
		 * Sends the registration ID to softtech vn
		 */
		private void sendRegistrationIdToBackend() {
			String url = ApplicationConstants.BASE_URL
					+ "gcmusers/register_gcm";
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			JSONObject json = new JSONObject();
			try {
				json.put("st_GcmId", REG_ID);
				json.put("st_GcmType", "0");//
			} catch (JSONException e) {
				e.printStackTrace();
			}
			params.add(new BasicNameValuePair("data", json.toString()));

			HttpRequest http = new HttpRequest();
			Log.v("", params.toString());//
			try {
				JSONObject jsonRequest = new JSONObject(http.makeServiceCall(
						url, HttpRequest.POST, params));
				success = jsonRequest.getInt("success");
			} catch (Exception e) {
			}
			;

		}

		@Override
		protected void onPostExecute(String result) {
			FileUtility fu = new FileUtility();
			if (success == 1) {
				fu.SaveContentFile(ActivityMain.this, SAVE_FILE, REG_ID);
			} else {
				Toast.makeText(ActivityMain.this, "not gcm id",
						Toast.LENGTH_LONG).show();
			}
			super.onPostExecute(result);
		}
	}
	
	/**
	 * start activity theo user
	 * @param user
	 */
	void startCodeActvitity(int user){
		
		switch (user) {
		case CASE_MUI:
			break;
		case CASE_HOAI:
			break;
		case CASE_QUAN:
			break;
		case CASE_PHUOC:
			startActivity(new Intent(mContext , ActivityCreateProduct.class));
			finish();
			break;

		default:
			break;
		}
	}
	
}
